package com.hue.netty.day02.four;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import java.util.Random;

/*
    客户端的处理器
 */
public class ClientHandler extends ChannelInboundHandlerAdapter {
    //通道准备就绪时会出发该方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //随机给服务器发送Student对象或者Teacher对象
        int i = new Random().nextInt(3);
        DataInfo.MyMessage message = null;
        if (i == 0) { //发送Student对象
            message = DataInfo.MyMessage.newBuilder().
                    setDataType(DataInfo.MyMessage.DataType.StudentType).
                    setStudent(DataInfo.Student.newBuilder().setId(2).setName("王五").build()).build();
        } else {  //发送Teacher对象
            message = DataInfo.MyMessage.newBuilder().
                    setDataType(DataInfo.MyMessage.DataType.TeacherType).
                    setTeacher(DataInfo.Teacher.newBuilder().setId(3).setName("张老师").setAge(30).build()).build();
        }
        ctx.writeAndFlush(message);
    }

    //有数据读取时触发
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //将消息转换为ByteBuf
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("客户端接收到服务器的消息：" + buf.toString(CharsetUtil.UTF_8));
    }
}
